<template>
  <div>
    <div class='play-container'>
      <a-button class="btn-back" v-show="viewHistory.length > 1" type="primary focusable" tabindex="-1" @click="closePlay" >
        返回
      </a-button>
      <a-spin class="spin-loading" size="large" v-show="!playing && loading"/>
      <div class="play_list" v-show="!playing && !loading">
        <div class="focusable file-item" :class="{'folder-item': item['isFolder']}" tabindex="-1" v-for="(item, index) in playList" :key='index' @click="playOne(index)" @keydown="keyDown(index, $event)">
          <div class="file_image" :style="{backgroundImage: 'url(https:' + (item.icon ? item.icon.largeUrl : '') + ')', backgroundSize:'contain'}"></div>
          <div class="file_info">
            <span class="file_name">{{item.fileName.replace('.mp4', '')}}</span>
          </div>
        </div>
      </div>
    </div>
    <div class="focusable player" tabindex="-1" v-show="playing" @keydown="playerKeyDown($event)">
      <video-player class="video-player vjs-custom-skin"
                    ref="videoPlayer"
                    :playsinline="true"
                    :options="playerOptions">
      </video-player>
    </div>
  </div>

</template>

<script>
  import SpatialNavigation from '../assets/js/spatial_navigation.js'
  export default {
    name: 'HelloWorld',
    props: {
      msg: String
    },
    data() {
      return {
        loading: false,
        viewHistory: ['-13'],
        playList: [],
        playIndex: 0,
        playTime: 0,
        playing: false,
        interval: null,
        fileId: '-13',
        playerOptions: {
          playbackRates: [0.5, 1.0, 1.5, 2.0], // 可选的播放速度
          autoplay: false, // 如果为true,浏览器准备好时开始回放。
          muted: false, // 默认情况下将会消除任何音频。
          loop: false, // 是否视频一结束就重新开始。
          preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
          language: 'zh-CN',
          aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
          fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
          sources: [{
            type: "video/mp4", // 类型
            // src: 'https://ccp-bj29-video-preview.oss-cn-beijing.aliyuncs.com/bj29/sha1_DC8D9F0D089DB064645A166DA259DFD512671D68_21687769_/FHD/master.mp4?Expires=1606064584&OSSAccessKeyId=LTAIsE5mAn2F493Q&Signature=znaeoNM82XMmaIupXzIPtEa25Hw=' // url地址
            // src: 'https://s3.us-west-1.wasabisys.com/et-test/Deadpool.2016.1080p.BluRay.x264.DTS-ETRG.mkv' // url地址
          }],
          poster: '', // 封面地址
          notSupportedMessage: '此视频暂无法播放，请稍后再试', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
          controlBar: {
            timeDivider: true, // 当前时间和持续时间的分隔符
            durationDisplay: true, // 显示持续时间
            remainingTimeDisplay: false, // 是否显示剩余时间功能
            fullscreenToggle: true // 是否显示全屏按钮
          }
        },
      }
    },
    computed: {
      player() {
        return this.$refs.videoPlayer.player
      }
    },
    mounted() {
      // this.playList.push({fileName: 'wasabi-iPhone的隐私-如此简单.mp4', download_url: 'https://download.cloud.189.cn/file/downloadFile.action?dt=51&expired=1609013913809&play=1&sk=9f0f9df0-421e-42b2-a8e7-bb74a9aa8084&ufi=31345212174227149&zyc=180&token=cloud15&sig=Cf3ThFmIiGuqZTVGo8GrqZWchGE%3D'})
      // this.playList.push({fileName: 'wasabi-Cinderella.Man.2005.720p.BluRay.H264.AAC-RARBG.MP4', download_url: 'https://download.cloud.189.cn/file/downloadFile.action?dt=51&expired=1609693235325&play=1&sk=b09a2212-f995-437c-8ef1-c9209d02cc48&ufi=31345212174227149&zyc=180&token=cloud16&sig=jBfaR0wqpTmFasXO2fxqgcw1xww%3D'})

      this.initData(this.fileId);
      window.addEventListener('load', function() {
        SpatialNavigation.init();
        SpatialNavigation.add({
          selector: 'a, .focusable'
        });
        SpatialNavigation.makeFocusable();
        SpatialNavigation.focus();
      });
    },
    methods: {
      closePlay() {
        this.viewHistory.pop()
        this.player.pause();
        this.playing = false;
        // if (this.interval) {
        //   clearInterval(this.interval)
        // }
        this.$set(this.playerOptions, 'autoplay', false)
        this.initData(this.viewHistory[this.viewHistory.length - 1])
      },
      initData(fileId) {
        this.loading = true
        let that = this
        this.$request.getFileList(fileId, function (data) {
          if (data.status === 200) {
            that.playList = Object.assign({}, data.data, {});
            that.loading = false
            // that.playList.push({
            //   fileName: 'wasabi-iPhone的隐私-如此简单.mp4',
            //   videoUrl: 'https://cloud.189.cn/downloadFile.action?fileStr=95AEE4BFB3B41D2C2FD4FFA661A4C393A2EC21191E3FC4D89340C36165C77800A962D5B8B71BE9A9347C6D4017CED003FBF175175FBFA9593EDA619E&downloadType=1'
            // })
            // that.playList.push({
            //   fileName: 'The.Croods.A.New.Age.2020.1080p.WEBRip.DD5.1.x264-CM.mkv',
            //   videoUrl: 'https://d1pchne27tofe2.cloudfront.net/The.Croods.A.New.Age.2020.1080p.WEBRip.DD5.1.x264-CM.mkv'
            // })
          }
        })
      },
      playOne(index) {
        let item = this.playList[index]
        if (item['isFolder']) {
          this.fileId = item['fileId']
          this.viewHistory.push(this.fileId)
          this.initData(this.fileId)
        } else {
          this.playIndex = index;
          const that = this
          this.playing = true;
          this.$request.getFileUrl(`https:${this.playList[index]['videoUrl']}`, function (data) {
            if (data.status === 200) {
              that.$set(that.playerOptions.sources, 0, {
                type: "video/mp4",
                src: data.data.url,
              })
              that.$set(that.playerOptions, 'autoplay', true)
              // that.player.requestFullscreen();
            }
          })
        }
      },
      keyDown(index, event) {
        if (event.key === 'Enter') {
          this.playOne(index)
        }
      },
      playerKeyDown(event) {
        console.log(event.key)
        // window.alert(event.key)
        switch (event.key) {
          case 'Enter':
            if (!this.player.isFullscreen()) {
              this.player.requestFullscreen();
            }
            break
          case 'Escape':
            if (this.player.isFullscreen()) {
              this.player.exitFullscreen();
            }
            break
        }
        // console.log(event.key)
        // window.alert(this.writeObj(event))
        // switch (event.key) {
        //   case 'Enter':
        //     if (!this.player.isFullscreen()) {
        //       this.player.requestFullscreen();
        //     }
        //     break
        //   case 'Escape':
        //     if (this.player.isFullscreen()) {
        //       this.player.exitFullscreen();
        //     }
        //     break
        // }
      },
      // playerReadied(player) {
      //   player.addRemoteTextTrack({ src: 'https://s3.us-west-1.wasabisys.com/et-test/[zmk.pw]Soul.2020.1080p.DSNP.WEBRip.DDP5.1.Atmos.x264-CM.zh-cn.vtt', kind: 'subtitles', srclang: 'ru', label:
      //         'English' });
      // },
      onPlayerTimeupdate(player) {
        this.playTime = player.currentTime()
        // console.log('player Timeupdate!', player.currentTime())
      },
      // or listen state event
      playerStateChanged(playerCurrentState) {
        if (playerCurrentState.error) {
          console.log('player current update state', playerCurrentState)
          const that = this
          // update src
          this.$set(this.playerOptions.sources, 0, {
            type: "video/mp4",
            src: this.playList[this.playIndex]['download_url'],
          })

          setTimeout(function () {
            that.player.currentTime(that.playTime)
            that.player.play()
          }, 1000)
          //
          // // set time out for init playList next time
          // setTimeout(function () {
          //   that.initData()
          // }, 1000 * 60 * 14)
        }
      },
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss">
  .play-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    .btn-back {
      width: fit-content;
    }
    .spin-loading {
      margin-top: 50px;
    }

    .play_list {
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
      column-gap: 15px;
      row-gap: 15px;
      justify-content: center;
      margin-top: 20px;
      .file-item {
        width: 350px;
        height: 150px;
        transform: translateY(0) scale(1);
        box-shadow: 0 8px 24px rgba(163,177,191,.35);
        display: flex;
        flex-direction: row;
        border-radius: 8px;
        background-color: #eee;
        z-index: 1;
        &:focus,&:hover {
          transform: translateY(-4px) scale(1.05);
          box-shadow: 0 12px 24px rgba(163,177,191,.55);
          background-color: #fff;
          border: 2px solid red;
          z-index: 2;
        }
        .file_image {
          width: 150px;
          height: 150px;
          min-width: 150px;
          border-radius: 8px 0 0 8px;
        }
        .file_info {
          padding: 10px;
          width: 200px;
          display: flex;
          flex-direction: column;
          .file_name {
            font-size: 18px;
            word-break: break-word;
          }
        }
      }
      .folder-item {
        .file_image {
          background-image: url('../assets/icon/folder.svg') !important;
        }
        .file_info {
          .file_name {
            font-size: 20px;
            font-weight: 700;
          }
        }
      }
    }
  }
  .player {
    margin-top: 20px;
  }
  h3 {
    margin: 40px 0 0;
  }

  ul {
    list-style-type: none;
    padding: 0;
  }

  li {
    display: inline-block;
    margin: 0 10px;
  }

  a {
    color: #42b983;
  }
</style>
